package cn.wolfcode.crm.serivce.impl;

import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.OrderBillItemMapper;
import cn.wolfcode.crm.mapper.OrderBillMapper;
import cn.wolfcode.crm.mapper.ProductStockMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.serivce.IOrderBillService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
public class OrderBillServiceImpl implements IOrderBillService {
    @Autowired
    private OrderBillMapper orderBillMapper;

    @Autowired
    private OrderBillItemMapper orderBillItemMapper;

    @Autowired
    private ProductStockMapper productStockMapper;


    @Override
    public void deleteByPrimaryKey(Long id) {
        orderBillMapper.deleteItemByBillId(id);
        orderBillMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(OrderBill record) {
        if (record.getId() == null) {
            //保存操作
            saveBill(record);
        }else {
            updateBill(record);
        }
    }


    //保存单据
    public void saveBill(OrderBill record){
        //设置录入人
        record.setInputUser(UserContext.getCurrentuser());
        //设置录入时间
        record.setInputTime(new Date());
        record.setVdate(new Date());
        //设置单据状态
        record.setStatus(OrderBill.NORMAL);

        //定义变量记录总数量和总价
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;

        //设置明细数据
        for (OrderBillItem item : record.getItems()) {
            BigDecimal number = item.getNumber();
            BigDecimal costPrice = item.getCostPrice();
            BigDecimal amount = number.multiply(costPrice).setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            //叠加总数量和总价
            totalNumber = totalNumber.add(number);
            totalAmount = totalAmount.add(amount);
        }
        record.setTotalNumber(totalNumber);
        record.setTotalAmount(totalAmount);
        //保存单据
        orderBillMapper.insert(record);

        //保存明细
        for (OrderBillItem item : record.getItems()) {
            item.setBillId(record.getId());
            orderBillItemMapper.insert(item);
        }

    }

    //更新单据
    public void updateBill(OrderBill record){
        //根据单据的ID查询完整信息
        OrderBill old = orderBillMapper.selectByPrimaryKey(record.getId());
        //为审核状态才能更新
        if(old.getStatus() == OrderBill.NORMAL){
            //删除当前所有明细
            orderBillMapper.deleteItemByBillId(old.getId());
            //定义变量记录总数量和总价
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            //设置明细数据
            for (OrderBillItem item : record.getItems()) {
                BigDecimal number = item.getNumber();
                BigDecimal costPrice = item.getCostPrice();
                BigDecimal amount = number.multiply(costPrice).setScale(2, RoundingMode.HALF_UP);
                item.setAmount(amount);
                //叠加总数量和总价
                totalNumber = totalNumber.add(number);
                totalAmount = totalAmount.add(amount);
                item.setBillId(old.getId());
                orderBillItemMapper.insert(item);
            }
            old.setTotalNumber(totalNumber);
            old.setTotalAmount(totalAmount);
            //回填
            old.setSn(record.getSn());
            old.setVdate(record.getInputTime());
            old.setSupplier(record.getSupplier());
            old.setDepot(record.getDepot());
            orderBillMapper.updateByPrimaryKey(old);
        }
    }


    @Override
    public OrderBill selectByPrimaryKey(Long id) {
        return orderBillMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult query(QueryObject qo) {
        Integer total = orderBillMapper.count(qo);
        if (total > 0) {
            List<OrderBill> rows = orderBillMapper.query(qo);

            return new PageResult(total,rows);
        }
        return new PageResult(0, Collections.EMPTY_LIST);
    }

    //审核入库
    public void audit(Long id) {
        //根据单据ID查询完整的信息
        OrderBill bill = orderBillMapper.selectByPrimaryKey(id);
        //检查当前单据的状态,未检查才能审核
        if(bill.getStatus() == OrderBill.NORMAL){
            Depot depot = bill.getDepot();
            //得到当前单据中所有的明细,依次入库
            for (OrderBillItem item : bill.getItems()) {
                Product p = item.getProduct();
                //查询当前商品所入的仓库中是否拥有该商品的库存
                ProductStock ps = productStockMapper.selectByProductAndDepot(p.getId(), depot.getId());
                if(ps != null){
                    //如果有库存,使用移动加权平均算法,重新计算库存价格
                    BigDecimal amount = item.getAmount().add(ps.getAmount());
                    BigDecimal number = item.getNumber().add(ps.getStoreNumber());
                    BigDecimal price = amount.divide(number).setScale(2, RoundingMode.HALF_UP);
                    //更新库存信息
                    ps.setPrice(price);
                    ps.setStoreNumber(number);
                    ps.setAmount(amount);
                    productStockMapper.updateByPrimaryKey(ps);
                }else {
                    //直接创建一个库存对象,存入数据库
                    ps = new ProductStock();
                    ps.setPrice(item.getCostPrice());
                    ps.setStoreNumber(item.getNumber());
                    ps.setAmount(item.getAmount());
                    ps.setProduct(p);
                    ps.setDepot(depot);
                    productStockMapper.insert(ps);
                }
            }
            //核心:填入审核人,审核时间,修改单据状态
            bill.setAuditTime(new Date());
            bill.setAuditor(UserContext.getCurrentuser());
            bill.setStatus(OrderBill.AUDIT);
            orderBillMapper.audit(bill);
        }
    }


}
